package com.usian.usianleadonewsuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.usianleadonewsuser.mapper.ApUserMapper;
import com.usian.usianleadonewsuser.mapper.AuthMapper;
import com.usian.usianleadonewsuser.service.AuthAppService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthAppServiceImpl implements AuthAppService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        if (!StringUtils.isEmpty(dto.getPassword())) {
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

            if (apUser != null) {
                String pswd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (pswd.equals(apUser.getPassword())) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("password", "");
                    map.put("salt", "");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user", apUser);
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");

            }
        } else {
            if (dto.getEquipmentId()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }else {
                Map<String,Object> map = new HashMap<>();
                map.put("token",AppJwtUtil.getToken(0l));
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }
    }
}
